<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="老人姓名" prop="elderName">
              <el-input v-model="queryParams.elderName" placeholder="请输入老人姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="证件号码" prop="idCard">
              <el-input v-model="queryParams.idCard" placeholder="请输入证件号码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="审核状态" prop="reviewStatus">
              <el-select v-model="queryParams.reviewStatus" placeholder="请选择审核状态" clearable>
                <el-option
                  v-for="dict in sys_review_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['nursing:elderBasic:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['nursing:elderBasic:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['nursing:elderBasic:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['nursing:elderBasic:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="elderBasicList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="老人id" align="center" prop="elderId" v-if="true" />
        <el-table-column label="老人照片" align="center" width="100">
          <template #default="scope">
            <image-preview v-if="scope.row.elderPhoto" :src="scope.row.elderPhotoUrl" :width="50" :height="50" />
            <span v-else>无照片</span>
          </template>
        </el-table-column>
        <el-table-column prop="elderName" label="老人姓名" show-overflow-tooltip />
        <el-table-column prop="gender" label="性别" align="center">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" align="center" />
        <el-table-column label="证件类型" align="center" prop="idCardType">
          <template #default="scope">
            <dict-tag :options="sys_card_type" :value="scope.row.idCardType"/>
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" align="center" show-overflow-tooltip />
        <el-table-column prop="isActive" label="是否在院" align="center">
          <template #default="scope">
            <dict-tag :options="sys_is_active" :value="scope.row.isActive"/>
          </template>
        </el-table-column>
        <el-table-column label="照护者" align="center" prop="caregiver" />
        <el-table-column prop="roomNumber" label="房间号" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.roomNumber" type="success" effect="plain">{{ scope.row.roomNumber }}</el-tag>
            <el-tag v-else type="info" effect="plain">未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column label="审核状态" align="center" prop="reviewStatus">
          <template #default="scope">
            <dict-tag :options="sys_review_status" :value="scope.row.reviewStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="button-group">
              <!-- 第一行按钮 -->
              <div v-if="scope.row.reviewStatus === '0'">
                <el-tooltip content="通过" placement="top">
                  <el-button link type="primary" icon="Check" @click="handleReview(scope.row, '1')" v-hasPermi="['nursing:elderBasic:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="拒绝" placement="top">
                  <el-button link type="primary" icon="Close" @click="handleReview(scope.row, '2')" v-hasPermi="['nursing:elderBasic:edit']"></el-button>
                </el-tooltip>
              </div>
              <!-- 第二行按钮 -->
              <div>
                <el-tooltip content="查看详情" placement="top">
                  <el-button link type="primary" icon="View" @click="handleViewDetails(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nursing:elderBasic:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nursing:elderBasic:remove']"></el-button>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改老人基础信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="elderBasicFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人照片" prop="elderPhoto">
          <image-upload v-model="form.elderPhoto" />
        </el-form-item>
        <el-form-item label="老人姓名" prop="elderName">
          <el-input v-model="form.elderName" placeholder="请输入老人姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker clearable
            v-model="form.birthDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="证件类型" prop="idCardType">
          <el-select v-model="form.idCardType" placeholder="请选择证件类型">
            <el-option
                v-for="dict in sys_card_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-input v-model="form.nation" placeholder="请输入民族" />
        </el-form-item>
        <el-form-item label="是否在院" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择是否在院">
            <el-option
                v-for="dict in sys_is_active"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家庭地址" prop="addressDetail">
          <el-input v-model="form.addressDetail" placeholder="请输入家庭地址" />
        </el-form-item>
        <el-form-item label="照护者" prop="caregiver">
          <el-input v-model="form.caregiver" placeholder="请输入照护者" />
        </el-form-item>
        <el-form-item label="入住日期" prop="admissionDate">
          <el-date-picker clearable
            v-model="form.admissionDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择入住日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="房间号" prop="roomId" v-if="false">
          <el-input v-model="form.roomId" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看老人详细信息对话框 -->
    <el-dialog :title="'老人详细信息 - ' + detailsForm.elderName" v-model="detailsDialog.visible" width="700px" append-to-body custom-class="elder-details-dialog">
      <div class="elder-details-container">
        <!-- 左侧照片区域 -->
        <div class="elder-photo-container">
          <div class="photo-wrapper">
            <image-preview v-if="detailsForm.elderPhoto" :src="detailsForm.elderPhotoUrl" :width="150" :height="150" />
            <el-avatar v-else :size="150" icon="el-icon-user-solid">无照片</el-avatar>
          </div>
          <div class="elder-name">{{ detailsForm.elderName }}</div>
          <div class="elder-status">
            <dict-tag :options="sys_is_active" :value="detailsForm.isActive" />
          </div>
          <div class="elder-room" v-if="detailsForm.roomNumber">
            <el-tag type="success" effect="plain">{{ detailsForm.roomNumber }}</el-tag>
          </div>
        </div>

        <!-- 右侧信息区域 -->
        <div class="elder-info-container">
          <!-- 基本信息 -->
          <div class="info-section">
            <div class="section-title">基本信息</div>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">性别：</span>
                <span class="info-value">
                  <dict-tag :options="sys_user_sex" :value="detailsForm.gender" />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">年龄：</span>
                <span class="info-value">{{ detailsForm.age }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">民族：</span>
                <span class="info-value">{{ detailsForm.nation || '未填写' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">血型：</span>
                <span class="info-value">{{ detailsForm.bloodType || '未填写' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出生日期：</span>
                <span class="info-value">{{ parseTime(detailsForm.birthDate, '{y}-{m}-{d}') || '未填写' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">照护者：</span>
                <span class="info-value">{{ detailsForm.caregiver || '未填写' }}</span>
              </div>
            </div>
          </div>

          <!-- 证件信息 -->
          <div class="info-section">
            <div class="section-title">证件信息</div>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">证件类型：</span>
                <span class="info-value">
                  <dict-tag :options="sys_card_type" :value="detailsForm.idCardType" />
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">证件号码：</span>
                <span class="info-value">{{ detailsForm.idCard || '未填写' }}</span>
              </div>
            </div>
          </div>

          <!-- 入住信息 -->
          <div class="info-section">
            <div class="section-title">入住信息</div>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">入住日期：</span>
                <span class="info-value">{{ parseTime(detailsForm.admissionDate, '{y}-{m}-{d}') || '未填写' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">审核状态：</span>
                <span class="info-value">
                  <dict-tag :options="sys_review_status" :value="detailsForm.reviewStatus" />
                </span>
              </div>
            </div>
          </div>

          <!-- 地址信息 -->
          <div class="info-section">
            <div class="section-title">地址信息</div>
            <div class="info-full-width">
              <span class="info-label">家庭地址：</span>
              <span class="info-value">{{ detailsForm.addressDetail || '未填写' }}</span>
            </div>
          </div>

          <!-- 健康信息 -->
          <div class="info-section">
            <div class="section-title">健康信息</div>
            <div class="info-full-width">
              <span class="info-label">健康状况简述：</span>
              <span class="info-value">{{ detailsForm.healthStatus || '未填写' }}</span>
            </div>
          </div>

          <!-- 备注信息 -->
          <div class="info-section" v-if="detailsForm.remarks">
            <div class="section-title">备注</div>
            <div class="info-full-width">
              <span class="info-value">{{ detailsForm.remarks }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="detailsDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ElderBasic" lang="ts">
import { listElderBasic, getElderBasic, delElderBasic, addElderBasic, updateElderBasic, reviewElderBasic } from '@/api/nursing/elderBasic';
import { ElderBasicVO, ElderBasicQuery, ElderBasicForm } from '@/api/nursing/elderBasic/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_is_active, sys_user_sex, sys_card_type, sys_review_status } = toRefs<any>(proxy?.useDict('sys_is_active', 'sys_user_sex', 'sys_card_type', 'sys_review_status'));

const elderBasicList = ref<ElderBasicVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const detailsForm = ref<ElderBasicForm>({
  elderId: undefined,
  elderName: undefined,
  elderPhoto: undefined,
  elderPhotoUrl: undefined,
  gender: undefined,
  birthDate: undefined,
  age: undefined,
  idCardType: undefined,
  idCard: undefined,
  nation: undefined,
  bloodType: undefined,
  isActive: undefined,
  addressDetail: undefined,
  caregiver: undefined,
  healthStatus: undefined,
  admissionDate: undefined,
  roomId: undefined,
  roomNumber: undefined,
  remarks: undefined,
  reviewStatus: undefined,
  reviewedBy: undefined,
  reviewTime: undefined
});

const queryFormRef = ref<ElFormInstance>();
const elderBasicFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const detailsDialog = reactive<DialogOption>({
  visible: false,
  title: '老人详细信息'
});

const initFormData: ElderBasicForm = {
  elderId: undefined,
  elderName: undefined,
  elderPhoto: undefined,
  elderPhotoUrl: undefined,
  gender: undefined,
  birthDate: undefined,
  age: undefined,
  idCardType: undefined,
  idCard: undefined,
  nation: undefined,
  bloodType: undefined,
  isActive: 2, // 默认设置为"不在院"(值为2)
  addressDetail: undefined,
  caregiver: undefined,
  healthStatus: undefined,
  admissionDate: undefined,
  roomId: undefined,
  roomNumber: undefined,
  remarks: undefined,
  reviewStatus: undefined,
  reviewedBy: undefined,
  reviewTime: undefined
}
const data = reactive<PageData<ElderBasicForm, ElderBasicQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elderName: undefined,
    idCard: undefined,
    reviewStatus: undefined,
    params: {
    }
  },
  rules: {
    elderId: [
      { required: true, message: "老人id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询老人基础信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listElderBasic(queryParams.value);
  elderBasicList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  elderBasicFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ElderBasicVO[]) => {
  ids.value = selection.map(item => item.elderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加老人基础信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ElderBasicVO) => {
  reset();
  const _elderId = row?.elderId || ids.value[0]
  const res = await getElderBasic(_elderId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改老人基础信息";
}

/** 提交按钮 */
const submitForm = () => {
  elderBasicFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.elderId) {
        await updateElderBasic(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addElderBasic(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ElderBasicVO) => {
  const _elderIds = row?.elderId || ids.value;
  await proxy?.$modal.confirm('是否确认删除老人基础信息编号为"' + _elderIds + '"的数据项？').finally(() => loading.value = false);
  await delElderBasic(_elderIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('nursing/elderBasic/export', {
    ...queryParams.value
  }, `elderBasic_${new Date().getTime()}.xlsx`)
}

/** 审核按钮操作 */
const handleReview = async (row: ElderBasicVO, reviewStatus: string) => {
  const statusText = reviewStatus === '1' ? '通过' : '拒绝';
  await proxy?.$modal.confirm(`确认要${statusText}该老人信息吗？`).finally(() => loading.value = false);
  await reviewElderBasic(row.elderId, reviewStatus);
  proxy?.$modal.msgSuccess(`审核${statusText}成功`);
  await getList();
}

/** 查看详情按钮操作 */
const handleViewDetails = async (row: ElderBasicVO) => {
  const res = await getElderBasic(row.elderId);
  Object.assign(detailsForm.value, res.data);
  detailsDialog.visible = true;
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.button-group > div {
  display: flex;
  justify-content: center;
}

/* 老人详情对话框样式 */
:deep(.elder-details-dialog) {
  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
    margin-right: 0;
    background-color: #f5f7fa;
  }

  .el-dialog__body {
    padding: 20px;
  }
}

.elder-details-container {
  display: flex;
  gap: 20px;

  .elder-photo-container {
    width: 180px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;

    .photo-wrapper {
      margin-bottom: 15px;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .elder-name {
      font-size: 18px;
      font-weight: bold;
      margin: 10px 0;
      color: #303133;
    }

    .elder-status {
      margin-bottom: 10px;
    }

    .elder-room {
      margin-top: 5px;
    }
  }

  .elder-info-container {
    flex: 1;

    .info-section {
      margin-bottom: 20px;
      background-color: #fff;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

      &:last-child {
        margin-bottom: 0;
      }

      .section-title {
        font-size: 16px;
        font-weight: bold;
        color: #409EFF;
        margin-bottom: 15px;
        padding-bottom: 8px;
        border-bottom: 1px solid #ebeef5;
      }

      .info-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
      }

      .info-item {
        display: flex;
        align-items: center;
      }

      .info-full-width {
        margin-bottom: 10px;
      }

      .info-label {
        color: #606266;
        font-weight: 500;
        margin-right: 5px;
        min-width: 90px;
        display: inline-block;
      }

      .info-value {
        color: #303133;
        word-break: break-all;
      }
    }
  }
}
</style>
